package com.zhanglijie.improve.atomic.three;

import java.util.HashSet;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/6 0006 23:41
 */
public class UnsafeCas {
    static  volatile Member member = new Member(1,"zhangsan",500);

    public static void main(String[] args) {

       // testOne();
        testTwo();
    }

    /**
     * 不安全的
     * Member{no=1, name='zhangsan', amount=605}
     * Member{no=1, name='zhangsan', amount=605}
     */
    public static void testOne(){
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < 2000; i++) {
            new Thread(()->{
                Member member_tmep = member;
                Member memberNew = new Member(member_tmep.getNo(), member_tmep.getName(), member_tmep.getAmount() + 1);
                member = memberNew;
                set.add(member.getAmount());

                System.out.println(member.toString());
                try{

                }catch (Exception e){}

            }).start();
        }
        try{
            Thread.sleep(5000);
        }catch (Exception e){}

        System.out.println(set.size());
    }

    /**
     * 加锁安全化
     */
    public static void testTwo(){
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < 20000; i++) {
            new Thread(()->{
                synchronized (UnsafeCas.class) {
                    Member member_tmep = member;
                    Member memberNew = new Member(member_tmep.getNo(), member_tmep.getName(), member_tmep.getAmount() + 1);
                    member = memberNew;
                    set.add(member.getAmount());

                    System.out.println(member.toString());
                    try {

                    } catch (Exception e) {
                    }
                }
            }).start();
        }
        try{
            Thread.sleep(5000);
        }catch (Exception e){}

        System.out.println(set.size());
    }
}
